package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.admin.pojos.AdSensitive;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.ISBN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private IWemediaClient wemediaClient;

    /**
     * 自媒体文章自动审核
     * @param id 自媒体文章id
     */
    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {

        if(id == null){
            throw new RuntimeException("文章id不存在");
        }

        //1.查询自媒体文章
        WmNews wmNews = wemediaClient.findNewsById(id);
        if(wmNews == null){
            throw new RuntimeException("文章不存在");
        }

        //2.文章状态为4，当前时间大于等于文章发布时间，保存数据
        if(wmNews.getStatus().equals(WmNews.Status.ADMIN_SUCCESS.getCode()) && System.currentTimeMillis() >= wmNews.getPublishTime().getTime()){
            saveAppArticle(wmNews);
            return;
        }


        //3.文章状态为8，当前时间大于等于文章发布时间，保存数据
        if(wmNews.getStatus().equals(WmNews.Status.SUCCESS.getCode()) && System.currentTimeMillis() >= wmNews.getPublishTime().getTime()){
            saveAppArticle(wmNews);
            return;
        }

        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //4.自管理敏感词审核  从内容中去找是否存在敏感词
            Map<String,Object> contentAndImages = handleTextAndImages(wmNews);
            boolean isSensitive = handleSensitive((String) contentAndImages.get("content"),wmNews);
            if(!isSensitive) return;

            //5.文章文本和文章图片审核
            boolean isTextScan = handleTextScan((String) contentAndImages.get("content"),wmNews);
            if(!isTextScan) return;

            boolean isImageScan = handleImageScan((List<String>)contentAndImages.get("images"),wmNews);
            if(!isImageScan) return;


            //6.发布时间不允许，修改状态为8
            if(wmNews.getPublishTime().getTime() > System.currentTimeMillis()){
                updateWmNews(wmNews,(short) 8,"审核成功，待发布");
                return;
            }

            //7.审核通过，保存app端相关文章
            saveAppArticle(wmNews);
        }

    }

    /**
     * 阿里云审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        if(images == null || images.size() == 0){
            return true;
        }

        boolean flag = true;
        try {
            //去重
            images = images.stream().distinct().collect(Collectors.toList());
            Map map = greenImageScan.imageScan(images);
            //审核失败
            if(map.get("suggestion").equals("block")){
                flag = false;
                updateWmNews(wmNews, (short) 2, "当前文章中存在违规图片内容");
            }
            //人工审核
            if(map.get("suggestion").equals("review")){
                flag = false;
                updateWmNews(wmNews, (short) 3, "当前文章中存在不确定图片内容");
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    /**
     * 阿里云审核文本
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greenTextScan.greeTextScan(content);
            //审核失败
            if(map.get("suggestion").equals("block")){
                flag = false;
                updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
            }
            //人工审核
            if(map.get("suggestion").equals("review")){
                flag = false;
                updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 修改自媒体文章
     * @param wmNews
     * @param status
     * @param msg
     */
    private void updateWmNews(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wemediaClient.updateWmNews(wmNews);
    }

    @Autowired
    private AdSensitiveMapper adSensitiveMapper;

    /**
     * 自管理敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {

        boolean flag = true;

        //初始化敏感词库
        //sclect  name form ad_sensitive
        List<AdSensitive> adSensitives = adSensitiveMapper.selectList(Wrappers.<AdSensitive>lambdaQuery().select(AdSensitive::getSensitives));
        List<String> allSensitive = adSensitives.stream().map(x -> x.getSensitives()).collect(Collectors.toList());
        SensitiveWordUtil.initMap(allSensitive);

        //文章内容匹配是包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(map.size() > 0){
            flag = false;
            //有敏感词
            updateWmNews(wmNews, (short) 2, "文章中包含了敏感词："+map);
        }
        return flag;
    }

    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 从自媒体文章中抽取文本内容和图片列表
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {


        //存储纯文本内容
        StringBuilder stringBuilder = new StringBuilder();

        //存储图片
        List<String> images = new ArrayList<>();

        //文章内容
        String content = wmNews.getContent();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        for (Map map : maps) {
            //文本内容
            if(map.get("type").equals("text")){
                stringBuilder.append(map.get("value"));
            }
            //图片内容
            if(map.get("type").equals("image")){
                String imageUrl = (String) map.get("value");
                //加上图片的前缀，为了能够正常访问图片
                if(!imageUrl.startsWith(webSite)){
                    imageUrl = webSite+imageUrl;
                }
                images.add(imageUrl);
            }

        }

        //文章封面的图片需要审核  sdjfsdjfdss.jpg,josjdofjsdof.jpg
        if(StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            for (String url : split) {
                if(!url.startsWith(webSite)){
                    url = webSite+url;
                }
                images.add(url);
            }
        }

        Map<String,Object> result = new HashMap<>();
        result.put("content",stringBuilder.toString());
        result.put("images",images);
        return result;
    }

    /**
     * 保存app端相关的文章
     * @param wmNews
     */
    private void saveAppArticle(WmNews wmNews) {
        //保存app文章
        ResponseResult responseResult = saveArticle(wmNews);
        if(!responseResult.getCode().equals(200)){
            throw new RuntimeException("文章审核，保存app端相关文章失败");
        }
        //设置自媒体文章对应的app端文章id
        Object data = responseResult.getData();
        wmNews.setArticleId((Long) data);
        updateWmNews(wmNews,(short) 9,"审核成功");


    }

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private AdChannelMapper adChannelMapper;

    /**
     * 调用远程接口保存数据
     * @param wmNews
     * @return
     */
    private ResponseResult saveArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        //设置文章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setPublishTime(wmNews.getPublishTime());
        dto.setContent(wmNews.getContent());
        dto.setImages(wmNews.getImages());
        dto.setLayout(wmNews.getType());
        dto.setTitle(wmNews.getTitle());
        dto.setCreatedTime(new Date());
        //频道
        AdChannel adChannel = adChannelMapper.selectById(wmNews.getChannelId());
        if(adChannel != null){
            dto.setChannelId(adChannel.getId());
            dto.setChannelName(adChannel.getName());
        }
        //设置作者
        WmUser wmUser = wemediaClient.findByUserId(wmNews.getUserId());
        if(wmNews != null){
            dto.setAuthorName(wmUser.getName());
        }
        return articleClient.saveArticle(dto);
    }
}
